<?php

/**
 * MYSQL类
 *
 */

class Mysql {

  var $link       = NULL;
  var $config     = array();
  var $version    = '';
  var $querynum  = 0;

  function __construct($config=array()) {
    $this->config['dbhost']   = 'localhost';
    $this->config['dbuser']   = '';
    $this->config['dbpw']     = '';
    $this->config['dbname']   = '';
    $this->config['charset']  = 'utf8';
    $this->config['pconnect'] = 0;
    $this->config['dbpre']    = 'fsdkp_';

    $this->config['filedir']  = '';
    $this->config['filename'] = '';
    $this->config['tables']   = array('*');

    $this->setconfig($config);
  }

  function __destruct() {
    $this->close();
  }

  function setconfig($config=array()) {
    if (!empty($config) && is_array($config)){
      foreach($config as $key=>$value) {
        $this->config[$key] = $value;
      }
    }
  }

  function connect($dbhost, $dbuser, $dbpw, $dbname='', $charset='utf8', $pconnect=0) {
    $func = $pconnect==0 ? 'mysql_connect' : 'mysql_pconnect';
    $this->link = @$func($dbhost, $dbuser, $dbpw) or die("Could not connect to $dbhost");
    $this->version = mysql_get_server_info($this->link);
    if ($this->version > '5.0.1') {
      mysql_query("set names '$charset'", $this->link);
    }
    if($dbname) {
      if(mysql_select_db($dbname, $this->link)) {
        return true;
      }
      else {
        return false;
      }
    }
    else {
      return true;
    }
  }

  function close() {
    return mysql_close($this->link);
  }

  function get($key) {
    return $this->config[$key];
  }
  
  function query($sql, $type='') {
    $sql = str_replace('@_@', $this->config['dbpre'], $sql);
    if ($this->link === NULL) {
      $this->connect($this->config['dbhost'], $this->config['dbuser'], $this->config['dbpw'], $this->config['dbname'], $this->config['charset'], $this->config['pconnect']);
    }
    $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
    if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
      die("MySQL Query Error: $sql");
    }
    $this->querynum++;
    return $query;
  }

  function getOne($sql, $type='', $result_type=MYSQL_ASSOC) {
    $query = $this->query($sql, $type);
    return mysql_fetch_array($query, $result_type);
  }

  function getAll($sql, $type='', $result_type=MYSQL_ASSOC) {
    $query = $this->query($sql, $type);
    $result = array();
    while($ret = mysql_fetch_array($query, $result_type)) {
      $result[] = $ret;
    }
    return $result;
  }

  function result($query, $row) {
    return @mysql_result($query, $row);
  }

  function insert_id() {
    return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
  }

  function affected_rows() {
    return mysql_affected_rows($this->link);
  }

  function num_rows($query) {
    return mysql_num_rows($query);
  }

  function num_fields($query) {
    return mysql_num_fields($query);
  }

  function free_result($query) {
    return mysql_free_result($query);
  }

  function querynum() {
    return $this->querynum;
  }


  function error() {
    return mysql_error($this->link);
  }

  function errno() {
    return mysql_errno($this->link);
  }


  function arr_insert($arr) {
    if (is_array($arr)) {
      $fstr = '';
      $vstr = '';
      foreach ($arr as $key => $val) {
        $fstr .= '`' . $key . '`, ';
        $vstr .= '\'' . $val . '\', ';
      }
      if ($fstr) {
        $fstr = ' (' . substr($fstr, 0, -2) . ') ';
        $vstr = ' (' . substr($vstr, 0, -2) . ') ';
        return $fstr . ' VALUES ' . $vstr;
      }
      else {
        return '';
      }
    }
    else {
      return '';
    }
  }

  function arr_update($arr) {
    if (is_array($arr)) {
      $ustr = '';
      foreach ($arr as $key => $val) {
        $ustr .= '`' . $key . '` = \'' . $val . '\', ';
      }
      return $ustr ? substr($ustr, 0, -2) : '';      
    }
    else {
      return '';
    }
  }


  function select_db($dbname) {
    $this->config['dbname'] = $dbname;
    return mysql_select_db($dbname, $this->link);
  }

  function fetch_assoc($query) {
    return mysql_fetch_assoc($query);
  }

  function fetch_fields($query) {
    return mysql_fetch_field($query);
  }


  function do_page($sql, $pagenumber=1, $pagesize=12) {
    $start = ($pagenumber-1) * $pagesize;
    $sql  .= ' LIMIT ' . $start . ', ' . $pagesize;
    return $this->getAll($sql);
  }

  function do_navi($sql, $pagenumber=1, $pagesize=12) {
    $total = $this->num_rows($this->query($sql));
    $pages = ceil($total / $pagesize);
    return array(
      total => $total,
      pages => $pages,
      page  => $pagenumber,
      pagesize => $pagesize
    );
  }

  function pagination($sql, $pagenumber=1, $pagesize=12) {
    $page = (int)$pagenumber;
    $size = (int)$pagesize;
    $page = $page>0 ? $page : 1;
    $size = $size>0 ? $size : 12;
    return array(
      $this->do_navi($sql,$page,$size),
      $this->do_page($sql,$page,$size)
    );
  }



  function makedir($dir) {
    $dirs = explode('/', dirname($dir));
    $tmp = '';
    foreach ($dirs as $dir) {
      $tmp .= $dir . '/';
      if (!file_exists($tmp) && !@mkdir($tmp, 0777))
        return $tmp;
    }
    return true;
  }

  function do_tables($tables) {
    if ($this->link === NULL) {
      $this->connect($this->config['dbhost'], $this->config['dbuser'], $this->config['dbpw'], $this->config['dbname'], $this->config['charset'], $this->config['pconnect']);
    }
    foreach($tables as $table) {
      if ($table == '*') {
        $table_new  = mysql_list_tables($this->config['dbname'],$this->link);
        $table_list = array();
        for ($i=0; $i < mysql_numrows($table_new); $i++) {
          array_push($table_list, mysql_tablename($table_new, $i));
        }
        $table_list = $table_list;
      }
      else{
        $table_list = $tables;
        break;
      }
    }
    return $table_list;
  }

  function backup() {
    $tables = $this->do_tables($this->config['tables']);
    $sqls   = '';
    foreach($tables as $tablename) {
      if($tablename == '') { continue; }
      $sqls .= "\nDROP TABLE IF EXISTS `$tablename`;\n";
      $rs    = $this->query("SHOW CREATE TABLE $tablename");
      $row   = mysql_fetch_row($rs);
      $sqls .= $row['1'].";\n\n";
      unset($rs);
      unset($row);

      $rs = $this->query("SELECT * FROM $tablename");
      $field = mysql_num_fields($rs);
      while($rows = mysql_fetch_row($rs)) {
        $comma = '';
        $sqls .= "INSERT INTO `$tablename` VALUES(";
        for($i=0;$i<$field;$i++) {
          $sqls .= $comma."'".$rows[$i]."'";
          $comma = ',';
        }
        $sqls .= ");\n";
      }
    }
    if(!empty($this->config['filename'])) {
      $sqlfile = $this->config['filedir'] . $this->config['filename'] . '.sql';
    }
    else {
      $sqlfile = $this->config['filedir'] . date("Y-m-d_H-i-s") .'.sql';
    }
    if ($this->makedir($sqlfile) !== true) {
      exit('can\'t create db_backup file');
    }
    file_put_contents($sqlfile, $sqls);
    return $sqlfile;
  }


}

?>